const userInfo = JSON.parse(sessionStorage.getItem('UserInfo')); //用户信息
const token = sessionStorage.getItem('token');
if (!userInfo && !token) {
  window.location.href = './login.html';
}
const root = userInfo.root;
import React from 'react';
import { Layout, Icon, Menu, Breadcrumb, Tag, Col, Button, Modal, Input, message } from 'antd';
import { Link } from 'react-router';
import Config from './common/config';
import LeftMenu from './common/leftMenu'
import $ from 'jquery';

//更新token
// $(document).ajaxSuccess(function (event, jqXHR, ajaxOptions, res) {
//   if (res && res.token) {
//     localStorage.setItem("token", res.token)
//   }
// })
//超时跳转
$(document).ajaxComplete(function (event, jqXHR, ajaxOptions, res) {
  if (jqXHR.status === 401) {
    sessionStorage.removeItem('UserInfo')
    sessionStorage.removeItem('token')
    sessionStorage.setItem('url', location.href)
    location.href = './login.html'
  }
})
const { Header, Footer, Sider, Content } = Layout;
const SubMenu = Menu.SubMenu;
const config = new Config();
const MenuItem = Menu.Item; //antd子菜单
export default class App extends React.PureComponent {
  constructor(props) {
    super(props);
    const urlHash = window.location.hash;
    const vals = urlHash.split('/'); //react路由hash地址数组
    const val = vals[1] === '' ? '/' : vals[1].split(':')[0]; //设置当前激活的菜单栏选项，默认是首页home
    const openkey = this.retCheckMenu(val); //菜单栏展开的一级菜单
    const taglist = sessionStorage.getItem('taglist'); //选中过的menu，做一个记录。用于页头标签渲染，历史记录
    this.state = {
      collapsed: false, //菜单折叠状态
      mode: 'inline', //菜单显示模式，垂直 or 行内
      taglist: taglist,
      value: val,
      openKey: [openkey],
      visible1: false,//安全退出
      visible: false,//修改密码
    };
    //绑定函数this 指向组件
    this.onCollapse = this.onCollapse.bind(this);
    this.selectMenu = this.selectMenu.bind(this);
  }
  componentWillMount() {

  }
  //菜单折叠函数
  onCollapse() {
    //console.log(collapsed)
    this.setState({
      collapsed: !this.state.collapsed,
      mode: !this.state.collapsed ? 'vertical' : 'inline',
    })
  }
  //菜单点击选择 记录点击的key 保存 用于标签tag渲染
  selectMenu(item) {
    let taglist = [];
    if (this.state.taglist) {
      taglist = JSON.parse(this.state.taglist);
    }
    //找到元素的name url对应的中文名
    taglist.push({ title: item.item.props.children.props.children, url: item.key });
    taglist = this.arrReduce(taglist); //taglist数组中存入的对象去重
    sessionStorage.setItem('taglist', JSON.stringify(taglist)); //存入session
    this.setState({
      taglist: JSON.stringify(taglist),
      value: item.key,
    });
  }
  //数组中对象元素去重
  arrReduce(arr) {
    //利用hash数组下标唯一方法对应对象的键和值
    let hash = [], newArr = [];
    //创建一个下标为数组中对象通用属性键值对的hash数组
    arr.forEach((item, i) => {
      hash[item.url] = item;
    })
    //console.log('hash',hash);
    //遍历hash数组 此哈希数组已经去重,然后创建一个新数组将hash数组的hash下标对应的值压入
    for (let key in hash) {
      //console.log('item',key,hash[key])
      newArr.push(hash[key]);
    }
    //console.log('newArr',newArr);
    //返回去重后的新数组
    return newArr;
  }
  //菜单展开回调
  getAncestorKeys(key) {
    const map = {
      sub3: ['sub2']
    };
    return map[key] || [];
  }
  //遍历整个config的菜单栏 用于匹配找到当前点击选中的key
  retCheckMenu(value) {
    //console.log('传入',value)
    for (const item of LeftMenu) {
      //console.log('主菜单',item);
      if (item) {
        for (const son of item.son) {
          //console.log('子菜单',son)
          if (son) {
            if (son.key === value) {
              return item.key
            }
          }
        }
      }
    }

  }

  onTagClose(item) {
    //console.log(item);
    let taglist = JSON.parse(this.state.taglist);
    let newlist = [];
    //console.log('标签列表',taglist);
    taglist.forEach(tag => {
      //console.log(tag.title != item.title)
      if (tag.title != item.title) {
        newlist.push(tag);
      }
    })
    //console.log('新数组',newlist);
    newlist = this.arrReduce(newlist);
    //console.log('新数组去重',newlist);
    sessionStorage.setItem('taglist', JSON.stringify(newlist));
    this.setState({
      taglist: JSON.stringify(newlist)
    }, () => { console.log(this.state.taglist) })
    //console.log(this.props.location);

  }
  safeExit() {
    this.setState({
      visible1: true,
    });
  }
  safeExithandleOk() {
    sessionStorage.removeItem("UserInfo");
    sessionStorage.removeItem('taglist');
    sessionStorage.removeItem('token');
    location.href = './login.html';
    this.setState({
      visible1: false
    });
  }
  safeExithandleCancel() {
    this.setState({
      visible1: false
    });
  }

  modifyPassword() {
    this.setState({
      visible: true,
    });
  }
  modifyPasswordHandleOk(e) {
    // console.log(userInfo)
    const { userid, originalPassword, newPassword, repeatPassword } = this.state;

    if (!originalPassword) {
      message.error(`请填写原始密码！`);
      return;
    }
    if (!newPassword) {
      message.error(`请填写新密码！`);
      return;
    }
    if (!repeatPassword) {
      message.error(`请填写重复新密码！`);
      return;
    }
    if (newPassword !== repeatPassword) {
      message.error(`两次密码不一致！`);
      return;
    }
    if (!/^(?=.*[A-Z])(?=.*[a-z])(?=.*\d).{8,}$/.test(newPassword)) {
      return message.error('密码不符合规则')
    }
    $.ajax({
      url: config.Priviliege + '/common/changePassword',
      type: "post",
      async: true,
      headers: { Authorization: 'Bearer ' + token },
      data: {
        // userid: userInfo.userid,
        password: this.state.originalPassword,
        newPassword: this.state.newPassword,
      },
      success: res => {
        if (res.code === 200) {
          this.setState({
            visible: false,
            originalPassword: '',
            newPassword: '',
            repeatPassword: '',
          });
          message.success('修改密码成功！')
        } else {
          message.error(res.msg)
        }
      }
    });

  }
  modifyPasswordHandleCancel() {
    this.setState({
      visible: false,
      originalPassword: '',
      newPassword: '',
      repeatPassword: '',
    });
  }
  menuKeyChange(key) {
    this.setState({
      value: key
    })
  }
  //输入原始密码
  inputOriginalPassword(e) {
    this.setState({
      originalPassword: e.target.value.replace(' ', ''),
    });
  }
  //输入新密码
  inputNewPassword(e) {
    this.setState({
      newPassword: e.target.value.replace(' ', ''),
    });
  }
  //输入重复新密码
  inputRepeatPassword(e) {
    this.setState({
      repeatPassword: e.target.value.replace(' ', ''),
    });
  }
  //tag标签点击
  clickTags(item) {
    console.log(item);
    this.setState({
      value: item.url
    }, () => {
      window.location.hash = '/' + item.url.split('-')[1];
    })
  }
  componentDidMount() {
    //console.log('子',this.props.children,this.props.children.type.name);
    if (userInfo.isFirst) {
      this.setState({ visible: true }, () => {
        userInfo.isFirst = false;
        //console.log('1',userInfo);
        sessionStorage.setItem("UserInfo", JSON.stringify(userInfo)); //用户信息
      })
    }
    //console.log(this.refs.header.clientWidth)
    this.refs.taglist.style.width = this.refs.header.clientWidth - 310 + 'px'
  }
  render() {
    let taglist = this.state.taglist ? JSON.parse(this.state.taglist) : [];

    let collapseImg = this.state.collapsed ? 'src/images/collapseRight.png' : 'src/images/collapseLeft.png'
    return (
      <Layout>
        <Header>
          <div style={{ height: '100%', lineHeight: '80px' }} ref='header'>
            <Link to='/' style={{ width: 200, textAlign: 'center', float: 'left' }}>
              <img src={require('../images/logo.png')} alt="" style={{ verticalAlign: 'middle' }} />
            </Link>
            <div>
              <span style={{ marginLeft: 20 }} ><img onClick={this.onCollapse} style={{ verticalAlign: 'middle' }} src={collapseImg} alt="" /></span>
              <div style={{ margin: '0 30px 0 20px', height: 80, float: 'right', whiteSpace: 'nowrap', overflowX: 'auto' }} ref='taglist'>
                <Tag>
                  <Link to='/' style={{ color: this.props.location.pathname === '/' ? '#e4393c' : '#999' }}>欢迎使用</Link>
                </Tag>
                {
                  taglist.map((item, i) => (
                    <span
                      key={i}
                      className='tags'
                      style={{ background: item.url === this.props.location.pathname.slice(1) ? '#59728d' : '#2a3e54' }}
                    >
                      <a onClick={this.clickTags.bind(this, item)}>{item.title}</a>
                      <span className='tagclose' onClick={this.onTagClose.bind(this, item)}>&times;</span>
                    </span>
                  ))
                }
              </div>
            </div>
          </div>
        </Header>
        <Layout style={{ overflow: 'auto' }}>
          <Sider
            collapsible
            collapsed={this.state.collapsed}
            trigger={null}
          >
            <div style={{ background: '#425566', marginBottom: 30, padding: '30px 0', minHeight: '100px', display: this.state.collapsed ? 'none' : 'block' }}>
              <div style={{ overflow: 'hidden', marginBottom: 10 }}>
                <Col span={12}><h1 style={{ color: '#fff', textAlign: 'right', paddingRight: 15 }}>欢迎</h1></Col>
                <Col span={12} style={{ color: '#dcdee1', paddingLeft: 15 }}><p>{root ? '超级管理员' : userInfo.userName}</p></Col>
              </div>
              <div className='center'>
                <Button className='menuBtn' onClick={this.safeExit.bind(this)} style={{ marginRight: 10 }}>安全退出</Button>
                <Modal
                  visible={this.state.visible1}
                  title="安全退出"
                  maskClosable={false}
                  onOk={this.safeExithandleOk.bind(this)}
                  onCancel={this.safeExithandleCancel.bind(this)}
                  className='welcomeModal'
                >
                  <p>确定退出当前账户</p>
                </Modal>
                <Button className='menuBtn' onClick={this.modifyPassword.bind(this)}>修改密码</Button>
                <Modal
                  visible={this.state.visible}
                  title="修改密码"
                  maskClosable={false}
                  onOk={this.modifyPasswordHandleOk.bind(this)}
                  onCancel={this.modifyPasswordHandleCancel.bind(this)}
                  className='welcomeModal'
                >
                  <p className="szma">原始密码<Input type="password" value={this.state.originalPassword} onChange={(e) => this.inputOriginalPassword(e)} placeholder="原始密码" autoComplete="off" /></p>
                  <p className="szma">设置密码<Input type="password" value={this.state.newPassword} onChange={(e) => this.inputNewPassword(e)} placeholder="新密码" autoComplete="off" /></p>
                  <p className="szma">重复密码<Input type="password" value={this.state.repeatPassword} onChange={(e) => this.inputRepeatPassword(e)} placeholder="重复新密码" autoComplete="off" /></p>
                  <p className="szma"><span>密码必须包含大、小写字母和数字、长度不小于8;</span></p>
                </Modal>
              </div>
            </div>
            <Menu
              theme="dark"
              mode={this.state.mode}
              onClick={this.selectMenu}
              selectedKeys={[this.state.value]}
              style={{ paddingBottom: 50 }}
            >
              {LeftMenu.map(sub => {
                if (sub) {
                  let MenuIcon = () => {
                    switch (sub.name) {
                      case '首页管理':
                        return <Icon type="home" />;
                      case '商品管理':
                        return <Icon type="gift" />;
                      case '营销管理':
                        return <Icon type="notification" />;
                      case '订单管理':
                        return <Icon type="book" />;
                      case '会员管理':
                        return <Icon type="solution" />;
                      case '组织管理':
                        return <Icon type="safety" />;
                      case '系统设置':
                        return <Icon type="setting" />;
                      case '直销管理':
                        return <Icon type="global" />;
                      case '权限设置':
                        return <Icon type="api" />;
                      case '橘色小工具':
                        return <Icon type="tool" />;
                      case '微信管理':
                        return <Icon type="apple-o" />;
                      case '换号小工具':
                        return <Icon type="swap" />;
                      case '官网管理':
                        return <Icon type="dingding" />;
                      case '在线问诊':
                        return <Icon type="pushpin-o" />;
                      case '支付中心':
                        return <Icon type="pay-circle-o" />;
                      case '健康调养':
                        return <Icon type="safety" />;
                      default:
                        return <Icon type="api" />;
                    }
                  };
                  return (
                    <SubMenu key={sub.key} title={<span><MenuIcon /><span>{sub.name}</span></span>}>
                      {
                        sub.son.length && sub.son.map(item => {
                          if (item) {
                            return item.son.length ?
                              <SubMenu key={item.key} title={<span><span>{item.name}</span></span>}>
                                {item.son.map(son => {
                                  if (son) {
                                    return (<Menu.Item key={son.key}>
                                      <Link to={son.url}>{son.name}</Link>
                                    </Menu.Item>)
                                  }
                                })}
                              </SubMenu>
                              :
                              <Menu.Item key={item.key}>
                                <Link to={item.url}>{item.name}</Link>
                              </Menu.Item>
                          }
                        })
                      }
                    </SubMenu>
                  )
                }
              })}
            </Menu>
          </Sider>
          <Content style={{ position: 'relative' }}>
            {this.props.children && React.cloneElement(this.props.children, { changeMenu: this.menuKeyChange.bind(this) })}
          </Content>
        </Layout>
      </Layout >
    )
  }
}